using System;
using SimpleJSON;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class AnimNumberHelper : NodeHelper
    {
        [SelectRef(UIKey.DATA_KEY)] public SelectKey beforeKey;
        public int before;

        public int time = 1;
        public bool animing;
        public AudioClip clip;
        private Action _cb;
        private int _i;
        private Text _Text;
        private float current;
        private float startTime;

        private Text Text
        {
            get
            {
                if (_Text == null) _Text = GetComponent<Text>();
                return _Text;
            }
        }

        protected override BindDataType bindDataType => BindDataType.Int;

        private void Update()
        {
            if (animing)
            {
                current = MathTools.clerp(before, _i, (Time.time - startTime) / time);
                if (current >= _i)
                {
                    current = _i;
                    animing = false;
                    if (_cb != null) _cb();
                    Emit(UIEvent.End);
                }

                Text.text = string.Format("{0:0}", current);
            }
        }

        public override void SetData(JSONObject json)
        {
            if (!beforeKey.IsEmpty()) before = beforeKey.Get(json).AsInt;
            base.SetData(json);
        }

        protected override void BindData(int i)
        {
            if (_i == i) return;
            _i = i;
            startTime = Time.time;
            animing = true;
            if (clip != null) Game.single.PlayEFF(clip);
        }

        public void Set(Action cb)
        {
            _cb = cb;
        }
    }
}